package com.swak.boot.config.im;

import static com.swak.boot.Application.APP_LOGGER;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.swak.Constants;
import com.swak.im.ImConfig;
import com.swak.im.ImService;
import com.swak.utils.StringUtils;
import com.swak.vertx.transport.VertxProxy;

/**
 * 简单的分布式IM服务
 * 
 * @author lifeng
 */
@Configuration
@ConditionalOnClass(ImService.class)
@EnableConfigurationProperties(DistributedImProperties.class)
@ConditionalOnProperty(prefix = Constants.APPLICATION_PREFIX, name = "enableIm", matchIfMissing = true)
public class DistributedImAutoConfiguration {

	@Autowired
	private DistributedImProperties properties;
	@Autowired
	private ApplicationContext context;

	public DistributedImAutoConfiguration() {
		APP_LOGGER.debug("Loading Distributed Im");
	}

	/**
	 * 加载服务配置处理器
	 * 
	 * @return
	 */
	@Bean
	public DistributedImAnnotationBeanPostProcessor DistributedImAnnotationBeanPostProcessor() {
		return new DistributedImAnnotationBeanPostProcessor();
	}

	/**
	 * 
	 * @return
	 */
	@Bean
	public ImService ImService(VertxProxy vertxProxy) {
		ImConfig config = new ImConfig().setConfigs(properties.getConfigs())
				.setApplicationName(context.getEnvironment().getProperty(Constants.Application_Name))
				.setModule(StringUtils.defaultIfBlank(properties.getModule(),
						context.getEnvironment().getProperty(Constants.Application_Name)));
		if (config.getWorkerPoolSize() <= 0) {
			config.setWorkerPoolSize(vertxProxy.config().getWorkerPoolSize());
		}
		return new ImService(config);
	}
}